package com.davy.gridpoint;


import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.provider.Settings;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.davy.gridpoint.utils.LogUtils;
import com.davy.gridpoint.utils.NetworkChangeReceiver;
import com.davy.gridpoint.utils.ToastUtil;
import com.davy.gridpoint.view.AndroidWorkaround;

import java.util.ArrayList;


public abstract class BaseActivity extends AppCompatActivity {
    protected Context mContext;
    protected boolean isConnected;

    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 设置只竖屏显示
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        mContext = this;
        if (AndroidWorkaround.checkDeviceHasNavigationBar(this)) { //适配华为手机虚拟键遮挡tab的问题
            AndroidWorkaround.assistActivity(findViewById(android.R.id.content));//需要在setContentView()方法后面执行
        }
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        requestPermissions(99);
        ScreenManager.getScreenManager().addActivity(this);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(networkChangeReceiver, intentFilter);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    protected void statusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//android6.0以后可以对状态栏文字颜色和图标进行修改
            getWindow().getDecorView()
                    .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        } else {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(R.color.white));// 改变标题栏背景颜色
            window.setNavigationBarColor(getResources().getColor(R.color.black));//改变标题栏字体颜色
        }
    }

    protected void statusbar4() {
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);//显示状态栏

        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
    }

    NetworkChangeReceiver networkChangeReceiver = new NetworkChangeReceiver(isConnected -> {
        LogUtils.e("TAG", "isConnected:" + isConnected);
        network(isConnected);
        // 这里处理网络状态变化
//        if (isConnected) {// 网络连接
//        } else {// 网络断开
//        }
    });

    protected void network(boolean isConnect) {
        isConnected = isConnect;
    }

    @Override
    protected void onResume() {
        super.onResume();
        //checkPermission();
    }

    //申请的权限放进数组里
    private static final String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    //请求状态码
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static final int REQUEST_PERMISSION_CODE_33 = 2;
    private AlertDialog dialog;
    private boolean havePermission;

    private void checkPermission() {
        //检查权限（NEED_PERMISSION）是否被授权 PackageManager.PERMISSION_GRANTED表示同意授权
        //这里是android11以上的读写权限申请
        //需要通过Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION跳转到权限设置打开权限
        if (Build.VERSION.SDK_INT >= 30) {
            if (!Environment.isExternalStorageManager()) {
                if (dialog != null) {
                    dialog.dismiss();
                    dialog = null;
                }
                dialog = new AlertDialog.Builder(this)
                        .setTitle("提示")//设置标题
                        .setMessage("请开启文件访问权限，否则无法正常使用本应用！")
                        .setNegativeButton("取消", (dialog, i) -> dialog.dismiss())
                        .setPositiveButton("确定", (dialog, which) -> {
                            dialog.dismiss();
                            Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                            startActivity(intent);
                        }).create();
                dialog.show();
            } else {
                havePermission = true;

            }
        } else {
            //这里就是android7到android11的权限申请
            //直接通过ActivityCompat.requestPermissions就可以
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    if (dialog != null) {
                        dialog.dismiss();
                        dialog = null;
                    }
                    dialog = new AlertDialog.Builder(this)
                            .setTitle("提示")//设置标题
                            .setMessage("请开启文件访问权限，否则无法正常使用应用！")
                            .setPositiveButton("确定", (dialog, which) -> {
                                dialog.dismiss();
                                ActivityCompat.requestPermissions(BaseActivity.this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
                            }).create();
                    dialog.show();
                } else {
                    havePermission = true;

                }
            } else {
                //android7以下的不需要动态申请权限
                havePermission = true;

            }
        }
    }

    // 请求权限
    public void requestPermissions(int requestCode) {
        try {
            if (Build.VERSION.SDK_INT >= 23) {
                ArrayList<String> requestPerssionArr = new ArrayList<>();
                int hasInternet = checkSelfPermission(Manifest.permission.INTERNET);
                if (hasInternet != PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.INTERNET);
                }
                int hasWIFIState = checkSelfPermission(Manifest.permission.SYSTEM_ALERT_WINDOW);
                if (hasWIFIState != PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.SYSTEM_ALERT_WINDOW);
                }
                int camera = checkSelfPermission(Manifest.permission.CAMERA);
                if (camera != PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.CAMERA);
                }
                int access_coarse_location = checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
                if (access_coarse_location != PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.ACCESS_COARSE_LOCATION);
                }
                int access_fine_location = checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
                if (access_fine_location != PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.ACCESS_FINE_LOCATION);
                }
                int storage = checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
                if (storage != PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission_group.STORAGE);
                }
                int manage_external_storage = checkSelfPermission(Manifest.permission.MANAGE_EXTERNAL_STORAGE);
                if (manage_external_storage != PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.MANAGE_EXTERNAL_STORAGE);
                }
                int access_network_state = checkSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE);
                if (access_network_state != PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.ACCESS_NETWORK_STATE);
                }
                int write_external_storages = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                if (write_external_storages != PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                }
                int read_external_storages = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
                if (read_external_storages != PERMISSION_GRANTED) {
                    requestPerssionArr.add(READ_EXTERNAL_STORAGE);
                }
                int request_install_packages = checkSelfPermission(Manifest.permission.REQUEST_INSTALL_PACKAGES);
                if (request_install_packages != PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.REQUEST_INSTALL_PACKAGES);
                }
                // 是否应该显示权限请求
                if (requestPerssionArr.size() >= 1) {
                    String[] requestArray = new String[requestPerssionArr.size()];
                    for (int i = 0; i < requestArray.length; i++) {
                        requestArray[i] = requestPerssionArr.get(i);
                    }
                    requestPermissions(requestArray, requestCode);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean flag = false;
        for (int i = 0; i < permissions.length; i++) {
            if (PERMISSION_GRANTED == grantResults[i]) {
                flag = true;
            }
        }
        switch (requestCode) {
            case REQUEST_EXTERNAL_STORAGE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    havePermission = true;
//                    ToastUtil.show("授权成功！");
                } else {
                    havePermission = false;
                    ToastUtil.show("授权被拒绝！");
                }
                break;
            case REQUEST_PERMISSION_CODE_33:
//                ToastUtil.show("授权成功！");
                break;
        }
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(networkChangeReceiver);
        super.onDestroy();
    }

    // 隐藏软键盘
    protected void hideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


    /**
     * 重写 getResource 方法，防止系统字体影响
     */
    @Override
    public Resources getResources() {//禁止app字体大小跟随系统字体大小调节
        Resources resources = super.getResources();
        Configuration configuration = new Configuration();
        configuration.setToDefaults();
        resources.updateConfiguration(configuration, resources.getDisplayMetrics());
        return resources;
    }
}
